package com.hyperfix.washer.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyperfix.models.washer.pojos.Monitor;
import com.hyperfix.washer.mapper.MonitorMapper;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JiangChunYu
 * 2024/4/14
 */
@Component
public class MonitorRegistrar implements DisposableBean {
    private final Map<Integer, Monitor> monitors = new ConcurrentHashMap<>(16);

    @Resource
    private MonitorMapper monitorMapper;

    public void addMonitor(Integer userId, Session session) {
        Monitor monitor = monitorMapper.selectOne(new LambdaQueryWrapper<Monitor>().eq(Monitor::getUserId, userId));
        monitor.setSession(session);
        this.monitors.put(userId, monitor);
    }

    public Monitor getMonitor(Integer userId) {
        return this.monitors.get(userId);
    }

    public void removeMonitor(Integer userId) {
        this.monitors.remove(userId);
    }

    public int currentUserNum() {
        return monitors.size();
    }

    public Collection<Monitor> getAllMonitor() {
        return monitors.values();
    }

    @Override
    public void destroy() {
        this.monitors.clear();
    }
}
